package com.aichat.ai_chatbackend.service.impl;

import com.aichat.ai_chatbackend.service.EmailService;
import com.aichat.ai_chatbackend.service.VerificationCodeService;
import com.aichat.ai_chatbackend.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务实现类
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private RedisUtil redisUtil;
    
    @Resource
    private EmailService emailService;

    // Redis Key 前缀
    private static final String EMAIL_CODE_PREFIX = "email:code:";
    private static final String EMAIL_SEND_LIMIT_PREFIX = "email:send:limit:";
    
    // 验证码有效期（分钟）
    private static final int CODE_EXPIRE_MINUTES = 5;
    // 发送间隔限制（秒）
    private static final int SEND_INTERVAL_SECONDS = 60;

    @Override
    public boolean sendEmailVerificationCode(String email) {
        // 检查是否可以发送
        if (!canSendCode(email)) {
            log.warn("邮箱 {} 发送验证码过于频繁", email);
            return false;
        }
        
        // 生成验证码
        String code = generateCode();
        
        // 发送邮件
        boolean emailSent = emailService.sendVerificationCode(email, code);
        if (!emailSent) {
            log.error("邮箱 {} 验证码邮件发送失败", email);
            return false;
        }
        
        // 存储验证码到 Redis
        String codeKey = EMAIL_CODE_PREFIX + email;
        redisUtil.setExValue(codeKey,code,CODE_EXPIRE_MINUTES,TimeUnit.MINUTES);
        
        // 设置发送限制
        String limitKey = EMAIL_SEND_LIMIT_PREFIX + email;
        redisUtil.setExValue(limitKey, "1", SEND_INTERVAL_SECONDS, TimeUnit.SECONDS);
        
        log.info("邮箱 {} 验证码发送成功", email);
        return true;
    }

    @Override
    public boolean verifyEmailCode(String email, String code) {
        if (email == null || code == null) {
            return false;
        }
        
        String codeKey = EMAIL_CODE_PREFIX + email;
        String storedCode = (String) redisUtil.getValue(codeKey);
        
        if (storedCode == null) {
            log.warn("邮箱 {} 的验证码已过期或不存在", email);
            return false;
        }
        
        boolean isValid = code.equals(storedCode);
        if (isValid) {
            // 验证成功后删除验证码
            redisUtil.delValue(codeKey);
            log.info("邮箱 {} 验证码验证成功", email);
        } else {
            log.warn("邮箱 {} 验证码验证失败", email);
        }
        
        return isValid;
    }

    @Override
    public boolean canSendCode(String email) {
        String limitKey = EMAIL_SEND_LIMIT_PREFIX + email;
        String limit = (String) redisUtil.getValue(limitKey);
        return limit == null; // 如果没有限制记录，说明可以发送
    }

    @Override
    public String generateCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000); // 生成100000-999999之间的数字
        return String.valueOf(code);
    }
} 